package com.shelpe.services.simbasync.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shelpe.services.simbasync.dao.OrderCustomerMapper;
import com.shelpe.services.simbasync.dao.PurchaseOrderMapper;
import com.shelpe.services.simbasync.model.OrderCustomer;
import com.shelpe.services.simbasync.model.OrderCustomerExample;
import com.shelpe.services.simbasync.model.PurchaseOrder;
import com.shelpe.services.simbasync.model.PurchaseOrderExample;
import com.shelpe.services.simbasync.model.Users;
import com.shelpe.services.simbasync.service.OrderCustomerService;
import com.shelpe.services.simbasync.service.UserService;
import com.shelpe.services.simbasync.service.simbaproxy.OrderProxy.PurchaseOrderDto;

@Service
public class OrderCustomerServiceImpl implements OrderCustomerService {

	private static final Logger logger = LoggerFactory.getLogger(OrderCustomerServiceImpl.class);
	
	@Autowired
	private OrderCustomerMapper mapper;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private PurchaseOrderMapper orderMapper;
	
	
	@Override
	public int deleteAllOrderCustomer() {
		// TODO Auto-generated method stub
		OrderCustomerExample example = new OrderCustomerExample();
		
		return mapper.deleteByExample(example);
	}

	@Override
	public List<OrderCustomer> getOrderCustomerFromRpt() {
		// TODO Auto-generated method stub
		List<OrderCustomer> list = mapper.selectOrderCustomerFromRpt();
		int id = 1;
		
		if(list == null){
			return list;
		}

		for(OrderCustomer item : list){

			Users user = userService.getUserByUserId(item.getUserId());
			item.setId(id++);
			item.setInit(true);
			
			if(user != null){
				item.setBalance(user.getBalance());
				item.setPurchaseExpires(user.getPurchaseExpires());
				item.setAuthorizedTo(user.getAuthorizedTo());
				item.setCreated(user.getCreatedTime());
				item.setPurchasedTime(user.getCreatedTime());//获取不到购买时间
			}else{
				logger.info("getOrderCustomerFromRpt userId: {} not find", item.getUserId());
				Date date = new Date();
				item.setBalance(BigDecimal.valueOf(0.00d));
				item.setPurchaseExpires(date);
				item.setAuthorizedTo(0L);
				item.setCreated(date);
				item.setPurchasedTime(date);
			}

			
			if(item.getImpressions() == null && item.getFavShopCount() == null && item.getCost() == null){
				item.setCpc(BigDecimal.valueOf(0.00d));
				item.setRoi(BigDecimal.valueOf(0.00d));
				item.setImpressions(0);
				item.setClick(0);
				item.setCost(BigDecimal.valueOf(0.00d));
				item.setDirectPay(BigDecimal.valueOf(0.00d));
				item.setIndirectPay(BigDecimal.valueOf(0.00d));
				item.setDirectPayCount(0);
				item.setIndirectPayCount(0);
				item.setFavShopCount(0);
				item.setFavItemCount(0);
			}
			
			item.setAuthorizedUsers("");
			item.setItemCode("");
			item.setCtr(BigDecimal.valueOf(0.00d));
			item.setCvr(BigDecimal.valueOf(0.00d));
			item.setSales(BigDecimal.valueOf(0.00d));
		}
		
		return list;
	}

	@Override
	public int insertOrderCustomerBatch(List<OrderCustomer> list) {
		// TODO Auto-generated method stub
		int num = 0;
		
		if(list != null && list.size() > 0){
			num = mapper.insertBatch(list);
		}
		
		return num;
	}
	
	@Override
	public List<PurchaseOrder> translateOrder(List<PurchaseOrderDto> dtoList){
		
		List<PurchaseOrder> result = new ArrayList<PurchaseOrder>();
		
		if(dtoList != null && dtoList.size() > 0){
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");		 
			String subStr = "个月"; 
			int subStrLen = subStr.length();
			Date tempDate = new Date();
			for(PurchaseOrderDto dto : dtoList){
				PurchaseOrder order = new PurchaseOrder();
				order.setArticleCode(dto.getArticleCode());
				order.setArticleName(dto.getArticleName());
				//logger.info(">>>translateOrder BizOrderId {}, nick {}, OrderId {}", dto.getBizOrderId(), dto.getNick(), dto.getOrderId());
				order.setBizOrderId(dto.getBizOrderId());
				order.setBizType(dto.getBizType());
				order.setCreateTime(tempDate);
				order.setOrderCycleEnd(tempDate);
				order.setOrderCycleStart(tempDate);
				
				try {
					order.setCreateTime(sdf.parse(dto.getCreate()));
				} catch (ParseException e1) {
					// TODO Auto-generated catch block
					logger.warn(">>>translateOrder Create {}", dto.getCreate());
					e1.printStackTrace();
				}
				try {
					order.setOrderCycleEnd(sdf.parse(dto.getOrderCycleEnd()));
				} catch (ParseException e1) {
					// TODO Auto-generated catch block
					logger.warn(">>>translateOrder OrderCycleEnd {}", dto.getOrderCycleEnd());
					e1.printStackTrace();
				}
				try {
					order.setOrderCycleStart(sdf.parse(dto.getOrderCycleStart()));
				} catch (ParseException e1) {
					// TODO Auto-generated catch block
					logger.warn(">>>translateOrder OrderCycleStart {}", dto.getOrderCycleStart());
					e1.printStackTrace();
				}
				
				order.setFee(Float.valueOf(dto.getFee()));
				order.setItemCode(dto.getItemCode());
				order.setItemName(dto.getItemName());
				order.setNick(dto.getNick());
				String orderCycle = dto.getOrderCycle();
				int orderCycleLen = orderCycle.length();
				order.setOrderCycle(0);
				if(orderCycle != null && orderCycle.endsWith(subStr)){
					orderCycle = orderCycle.substring(0, orderCycleLen - subStrLen);
					try{
						Integer cycle = Integer.valueOf(orderCycle);
						if(cycle != null){
							int type = 0;
							if(cycle >= 12){
								type = 1;
							}else if(cycle >= 1){
								type = 2;
							}else{
								type = 3;
							}
							order.setOrderCycle(type);
						}
					}catch(Exception e){
						logger.warn(">>>translateOrder OrderCycle1 {}", dto.getOrderCycle());
					}
				}else{
					logger.warn(">>>translateOrder OrderCycle2 {}", dto.getOrderCycle());
				}
				
				order.setOrderId(dto.getOrderId());
				order.setPromFee(Float.valueOf(dto.getPromFee()));
				order.setRefundFee(Float.valueOf(dto.getRefundFee()));
				order.setTotalPayFee(Float.valueOf(dto.getTotalPayFee()));
				//order.setVersionNo(versionNo);
				//order.setOrderStatus(orderStatus);
				//order.setPayStatus(payStatus);
				
				result.add(order);
			}
		}
		
		return result;
	}
	
	@Override
	public Date getLastTimeFromOrder(String articleCode){
		
		return orderMapper.getLastTime(articleCode);
	}
	
	@Override
	public int deleteOrderByTimeRange(String articleCode, Date startTime, Date endTime){
		
		PurchaseOrderExample example = new PurchaseOrderExample();
		example.createCriteria().andArticleCodeEqualTo(articleCode)
				.andCreateTimeBetween(startTime, endTime);
		
		return orderMapper.deleteByExample(example);
	}
	
	@Override
	public int insertOrderBatch(List<PurchaseOrder> list){
		
		int num = 0;
		int pageSize = 10000;
		if(list != null && list.size() > 0){
			int fromIndex = 0;
			int endIndex = 0;
			do{
				endIndex += pageSize; 
				if(endIndex > list.size()){
					endIndex = list.size();
				}
				num += orderMapper.insertBatch(list.subList(fromIndex, endIndex));	
				fromIndex += pageSize; 
			
			}while(fromIndex < list.size());
		}
		
		return num;
	}

}
